var app = getApp();
var ajax = require('./ajax.js');
var Config = require('../config.js');

var isExtInited = false;
var sysInfo = undefined;

//初始化app
function initApp(options) {
    var {
        extSuc,
        loginSuc,
        sysInfoSuc,
        fetchSysInfo = false, //是否强制获取系统信息
    } = options || {};

    initExtConfig(function() {
        extSuc && extSuc();

        quietLogin(function() {
            loginSuc && loginSuc();

            getSysInfo((sysInfo) => {
                sysInfoSuc && sysInfoSuc(sysInfo);
            }, fetchSysInfo);
        });
    });
}

//读取系统信息
function getSysInfo(cb, fetchSysInfo) {

    if (!fetchSysInfo && sysInfo) {
        return cb && cb(sysInfo);
    }

    wx.getSystemInfo({
        complete: (res) => {
            const {
                windowHeight,
                windowWidth
            } = res;

            sysInfo = res;
            windowHeight && app.setWinHei(windowHeight);
            windowWidth && app.setWinWid(windowWidth);

            cb && cb(res);
        },
    });
}

//初始化配置信息
function initExtConfig(cb) {
    if (isExtInited) {
        return cb && cb();
    }
    wx.getExtConfig && wx.getExtConfig({
        success: function(res) {
            var {
                host,
                alias,
                tabBar
            } = res.extConfig;

            isExtInited = true;
            if (host) {
                app.setHost(host);
            }
            if (alias) {
                app.setAlias(alias);
            }
            if (tabBar) {
                app.config.tabBar = tabBar;
            }
            cb && cb();
        }
    });
}

/**
 * 静默登陆
 */
function quietLogin(cb) {
    //检验登录态是否过期
    wx.checkSession({
        success: function() { //session没有过期
            if (app.getOpenId() || app.getUserSid()) {
                cb && cb();
                return;
            }
            doLogin(cb);
        },
        fail: function() { //session已过期
            doLogin(cb);
        }
    });
}

function doLogin(cb) {
    wx.login({
        success: function(res) {

            app.getUserInfo(function(userInfo) {
                var params = {
                    jscode: res.code,
                };

                if (userInfo) {
                    params.nickName = userInfo.nickName;
                    params.avatarUrl = userInfo.avatarUrl;
                }

                ajax.P({
                    url: '/common/User/index',
                    data: params,
                    success: (res) => {
                        var data = res.result;
                        var appType = data.app_type;
                        var openid = data.openid;
                        var sid = data.sid;
                        var userSid = data.userSid;
                        var user_id = data.user_id;
                        var techId = data.tech_id;
                        var logoImg = data.logo;
                        var shareTitle = data.share_title;
                        var marketTitle = data.title;

                        app.globalData.sid = sid || '';
                        if (openid) {
                            app.setOpenId(openid);
                        }
                        if (userSid) {
                            app.setUserSid(userSid);
                        }
                        if (user_id) {
                            app.setUserId(user_id);
                        }
                        if (data.copyright) {
                            app.globalData.copyright = data.copyright;
                        }

                        if (marketTitle) {
                            app.setMarketTitle(marketTitle);
                        }

                        if (logoImg) {
                            app.setLogoImg(logoImg);
                        }
                        if (shareTitle) {
                            app.setShareTitle(shareTitle);
                        }

                        app.globalData.modList = data.module_list || []; //功能模块
                        app.globalData.appType = appType;

                        cb && cb();
                    }
                });
            });
        },
        fail: function() {},
        complete: function() {}
    });
}

function jump(evt) {
    var formId = evt.detail.formId;
    var {
        openType,
        url,
        mustLogin
    } = evt.currentTarget.dataset
    var isLogin = !!app.getUserSid();

    if (mustLogin && !isLogin) {
        wx.navigateTo({
            url: '/pages/login/index'
        });
        return;
    }

    if (openType == 'navigate' || !openType) {
        openType = 'navigateTo';
    }

    wx[openType]({
        url
    });
    submitForm(formId);
}

//提交表单id
function submitForm(formId) {
    if (!formId) {
        return;
    }
    ajax.P({
        url: '/common/User/addFormId',
        data: {
            openId: app.getOpenId(),
            formId
        },
        success: function(res) {}
    });
}

//提交支付id
function submitPrepay(prepayId) {
    if (!prepayId) {
        return
    }
    ajax.P({
        url: '/common/User/addPrePayId',
        data: {
            openId: app.getOpenId(),
            prepayId,
        },
        success: function(res) {}
    });
}

const pageMedhods = ['onLoad', 'onReady', 'onShow', 'onHide', 'onUnload', 'onPullDownRefresh', 'onReachBottom', 'onShareAppMessage', 'onPageScroll'];

function extend(Child, Parent) {　　　　
    var F = function() {};　　　　
    F.prototype = Parent.prototype;　　　　
    Child.prototype = new F();
    Child.prototype.constructor = Child;　　　　
    Child.uber = Parent.prototype;
}

//合并两个Page对象
function extendPage(source, obj) {
    if (!source || !obj) {
        return;
    }
    var newObj = {};
    var newData = {};

    Object.assign(newData, source['data']);
    Object.assign(newData, obj['data']);

    Object.assign(newObj, source);
    Object.assign(newObj, obj);

    newObj['data'] = newData;

    pageMedhods.forEach(function(methodName) {
        var sourceFunc = source[methodName];
        var objFunc = obj[methodName];

        if (sourceFunc && objFunc) {
            newObj[methodName] = function(...params) {
                sourceFunc.bind(this)(...params);
                objFunc.bind(this)(...params);
            }
        }
    });

    return newObj;
}

var pageIndex = 0;
var pageList = ['/pages/mPage1/index', '/pages/mPage2/index', '/pages/mPage3/index'];

//跳转到某个自定义页面
function goToPage(pageId) {
    if (!pageId) {
        return;
    }
    var openType = 'navigateTo';
    var maxIndex = pageList.length - 1;
    var tabBar = app.config.tabBar;
    var toBarName;

    if (pageIndex > maxIndex) {
        openType = 'redirectTo';
    }

    if (tabBar) {
        Object.keys(tabBar).some(function(key) {
            if (tabBar[key] == pageId) {
                openType = 'switchTab';
                toBarName = key;
                return true;
            }
        });
    }

    if (openType == 'switchTab') {
        wx[openType]({
            url: '/pages/' + toBarName + '/index'
        });
        pageIndex = 0;
    } else {
        wx[openType]({
            url: pageList[pageIndex > maxIndex ? maxIndex : pageIndex] + '?pageId=' + pageId
        });
        pageIndex++;
    }
}

function goBackPage() {
    pageIndex--;
}

module.exports = {
    initApp,
    quietLogin,
    submitForm,
    jump,
    extend,
    extendPage,
    goToPage,
    goBackPage,
    submitPrepay
};